import React, { useRef, useState, useEffect } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getList,
  setStatus,
  del,
  setSorts,
  delAll,
  getTypeList,
} from '@/services/blogAdmin/article/article/api';
import { Switch, Space, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { exportExcel } from '@/utils/ExportExcel';
import { getSort, setLsetData } from '@/utils/utils';
import FormIndex from './components/FormIndex';
import NumberInput from '@/components/common/NumberInput';
import CDel from '@/components/common/CDel';
import CDelAll from '@/components/common/CDelAll';

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [typeList, setTypeList] = useState<any>([]);
  // const [selectedRowsCope, setSelectedRowsCope] = useState<any>([]);
  // const getSelectedRows = () =>
  //   new Promise((resolve) => {
  //     setSelectedRowsCope((oldState: any) => {
  //       resolve(oldState);
  //       return oldState;
  //     });
  //   });
  const fetchApi = async () => {
    const typeRes = await getTypeList();
    if (typeRes.status == 20000) {
      // const groupData = [];
      // for (let i = 0; i < groupRes.data.length; i++) {
      //   groupData[groupRes.data[i].id] = {
      //     text: groupRes.data[i].name,
      //     status: groupRes.data[i].id,
      //   };
      // }
      // if (groupData.length)
      await setTypeList(typeRes.data);
    }
  };
  useEffect(() => {
    fetchApi();
  }, []);
  let maps = {};
  const columns: ProColumns<API.BlogAdminArticleList>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      hideInSearch: true,
      align: 'center',
      width: 80,
      fixed: true,
    },
    {
      title: '文章名称',
      dataIndex: 'name',
      align: 'center',
      width: 100,
      render: (text, record) => (
        <Space>
          <a className="overflow-wrap" href="https://www.baidu.com" target="_blank">
            {record.name}
          </a>
        </Space>
      ),
    },
    {
      title: '文章类型',
      dataIndex: 'article_to',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [<span key={record.id}>{record.article_to?.name}</span>],
    },
    {
      title: '文章类型',
      dataIndex: 'article_type_id',
      valueType: 'cascader',
      fieldProps: { options: typeList, fieldNames: { value: 'id', label: 'name' } },
      hideInTable: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
      sorter: true,
      width: 80,
      align: 'center',
      render: (text, record) => [
        <NumberInput
          key={record.id}
          value={record.sort}
          onBlur={async (value: number) => {
            const res = await setSorts(record.id, { sort: value });
            if (res.status === 20000) {
              message.success(res.message);
            } else {
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '禁用',
          status: '0',
        },
        1: {
          text: '启用',
          status: '1',
        },
      },
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [
        <Switch
          key={record.id + record.status}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.status === 1 ? true : false}
          onChange={async (checked: boolean) => {
            const res = await setStatus(record.id, { status: checked ? 1 : 0 });
            if (res.status === 20000) {
              message.success(res.message);
            } else {
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },

    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'created_at[0]': value[0],
            'created_at[1]': value[1],
          };
        },
      },
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            updated_at: value,
          };
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, row) => [
        <FormIndex
          id={row.id}
          key={row.id}
          onConfirm={() => {
            return actionRef.current?.reload();
          }}
        />,
        <CDel
          key={row.id}
          onCancel={async () => {
            const res = await del(row.id);
            if (res.status === 20000) {
              message.success(res.message);
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
  ];
  return (
    <PageContainer fixedHeader={true} title={false}>
      <ProTable
        scroll={{ x: 1300 }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params: any, sort) => {
          if (params.article_type_id) {
            params.article_type_id = params.article_type_id[params.article_type_id.length - 1];
          }
          const data: any = await getSort(params, sort);
          const res = await getList(data);
          return setLsetData(res);
        }}
        options={{ fullScreen: true }}
        rowSelection={{ fixed: true }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        columnsState={{
          onChange: (map) => {
            maps = map;
          },
        }}
        tableAlertOptionRender={({ selectedRows, selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={16}>
              <CDelAll
                key={selectedRowKeys.length}
                count={selectedRowKeys.length}
                onCancel={async () => {
                  const res = await delAll({ idArr: selectedRowKeys });
                  if (res.status === 20000) {
                    message.success(res.message);
                    actionRef.current?.reload();
                    onCleanSelected();
                  }
                }}
              />
              <a
                onClick={() => {
                  const selectedRowsCope = JSON.parse(JSON.stringify(selectedRows));
                  selectedRowsCope.map((item: any) => {
                    item.article_to = item.article_to?.name || '';
                    return item;
                  });
                  exportExcel({
                    fileName: '文章列表',
                    columns,
                    maps,
                    selectedRows: selectedRowsCope,
                  });
                }}
              >
                导出数据
              </a>
            </Space>
          );
        }}
        headerTitle={
          <FormIndex
            onConfirm={() => {
              return actionRef.current?.reload();
            }}
          />
        }
      />
    </PageContainer>
  );
};
export default Index;
